<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'bas:mes:oper:basMesOper:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsBasMesOperBasMesOperForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed, reactive  } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasMesOper, basMesOperSave, basMesOperForm } from '/@/api/bas/mes/oper/basMesOper';
  import { basWorkShopTreeData } from '/@/api/bas/mes/workshop/basMesWorkShop';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('bas.mes.oper.basMesOper');
  const { showMessage } = useMessage();
  const record = ref<BasMesOper>({} as BasMesOper);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增工序档案') : t('编辑工序档案'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('工序编码'),
      field: 'code',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
    },
    {
      label: t('工序名称'),
      field: 'name',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('归属车间'),
      field: 'workShopCode',
      fieldLabel: 'workShop.name',
      component: 'TreeSelect',
      componentProps: {
        api: basWorkShopTreeData,
        allowClear: true,
        canSelectParent: false,
      },
      required: true,
    },
    {
      label: t('计价方式'),
      field: 'costType',
      component: 'RadioGroup',
      componentProps: {
        dictType: 'mes_price_mode',
      },
      required: true,
    },
    {
      label: t('技能标准'),
      field: 'techLevel',
      component: 'RadioGroup',
      componentProps: {
        dictType: 'mes_tech_level',
      },
      required: true,
    },
    {
      label: t('技能控制'),
      field: 'techCtrl',
      component: 'RadioGroup',
      componentProps: {
        dictType: 'mes_tech_ctrl',
      },
      required: true,
    },
    {
      label: t('报工方式'),
      field: 'reportType',
      component: 'RadioGroup',
      componentProps: {
        dictType: 'mes_report_type',
      },
      required: true,
    },
    {
      label: t('关键工序'),
      field: 'bkey',
      component: 'Checkbox',
      componentProps: ({ formModel }) => {
        return {
          options: [{ label: '', value: 1 }],
          onChange: (v) => {
            console.log(v.target);
            formModel['bkey'] = v.target.checked ? 1 : 0;
          },
        };
      },
      //required: true,
    },
    {
      label: t('是否委外'),
      field: 'bout',
      component: 'Checkbox',
      componentProps: ({ formModel }) => {
        return {
          options: [{ label: '', value: 1 }],
          onChange: (v) => {
            console.log(v.target);
            formModel['bout'] = v.target.checked ? 1 : 0;
          },
        };
      },
      //required: true,
    },
    {
      label: t('是否报工'),
      field: 'breport',
      component: 'Checkbox',
      componentProps: ({ formModel }) => {
        return {
          options: [{ label: '', value: 1 }],
          onChange: (v) => {
            console.log(v.target);
            formModel['breport'] = v.target.checked ? 1 : 0;
          },
        };
      },
      //required: true,
    },
    {
      label: t('是否检验'),
      field: 'bcheck',
      component: 'Checkbox',
      componentProps: ({ formModel }) => {
        return {
          options: [{ label: '', value: 1 }],
          onChange: (v) => {
            console.log(v.target);
            formModel['bcheck'] = v.target.checked ? 1 : 0;
          },
        };
      },
      //required: true,
    },
    {
      label: t('是否上机'),
      field: 'bmachine',
      component: 'Checkbox',
      componentProps: ({ formModel }) => {
        return {
          options: [{ label: '', value: 1 }],
          onChange: (v) => {
            console.log(v.target);
            formModel['bmachine'] = v.target.checked ? 1 : 0;
          },
        };
      },
      //required: true,
    },
    {
      label: t('备注说明'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });
  // propertiesToToggle 为响应式数组
  const propertiesToToggle = reactive(['bcheck', 'bout', 'breport', 'bkey']);
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await basMesOperForm(data);
    record.value = (res.basMesOper || {}) as BasMesOper;
    record.value.__t = new Date().getTime();
    toggleBooleanValues(record.value, propertiesToToggle);
    setFieldsValue(record.value);
    updateSchema([
      {
        field: 'code',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
    ]);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        code: record.value.code,
      };
      toggleBooleanProperties(data, propertiesToToggle);
      console.log('submit', params, data, record);
      const res = await basMesOperSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
  function toggleBooleanValues(obj, keys) {
    keys.forEach(key => {
      obj[key] = obj[key] == 1 ? true : false;
    });
  }
  function toggleBooleanProperties(data, properties) {
    properties.forEach((property) => {
      data[property] = toggleBooleanToInt(data[property]);
    });
  }
  function toggleBooleanToInt(value) {
    return value ? 1 : 0;
  }
</script>
